<template>
  <a-modal width="760px" :visible="visible" :title="TITLE[showType]" @cancel="handleCancel">
    <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="directoryRef" />
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="state.loading" @click="handleOk">{{ OK_TEXT[showType] }}</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue';
import { DynamicForm } from '@/components/public-template';
import { RESETTABLE } from '@/mixins/subject/subject-types';
import viewService from './viewDialog.service';
import { message } from 'ant-design-vue';
import { directorySave } from '@/config/api/personFile';
import { changeByte } from '@/utils/common';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object
  },
  // VIEW：查看 EDIT：编辑
  showType: {
    type: String,
    default: ''
  }
});
const emit = defineEmits(['update:visible', 'handleEdit']);
const state = reactive({
  loading: false
});
const TITLE = {
  VIEW: '个人文件夹详情',
  EDIT: '编辑个人文件夹'
};
const OK_TEXT = {
  VIEW: '编辑',
  EDIT: '确定'
};
const directoryRef = ref(null);
const { proxy }: any = getCurrentInstance();
const dyConfig: any = {
  type: 'layer',
  grid: 12,
  labelCol: 12,
  wrapperCol: 24,
  layout: 'vertical',
  cancelSave: true,
  data: props.data,
  beforeWithMethod: (from) => {
    const data = JSON.parse(JSON.stringify(from));
    data.size = changeByte(data.size);
    data.type = data.folder ? '文件夹' : data.suffix && data.suffix.toLocaleUpperCase();
    return data;
  }
};
const dyQuestions: any = reactive(props.showType == 'VIEW' ? viewService.getViewQuestions() : viewService.getQuestions());
function handleOk() {
  if (props.showType == 'VIEW') {
    emit('handleEdit', props.data);
  } else {
    directoryRef.value.onFinish((params) => {
      state.loading = true;
      directorySave(params)
        .then((result) => {
          if (result.success) {
            message.success(`${props.showType == 'ADD' ? '添加' : '修改'}成功`);
            proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'personFile' } });
            emit('update:visible', false);
          }
          state.loading = false;
        })
        .catch((err) => {
          state.loading = false;
          return Promise.reject(err);
        });
    });
  }
}
function handleCancel() {
  emit('update:visible', false);
}
</script>

<style lang="less" scoped></style>
